const { searchRecord, searchItems, addRecord } = require('../../utils/feishuAPI');
Page({
  data: {
    dataArray: [],
    question: '',
    answer: '',
    tags: [{
      value: 'loading',
      name: '加载中',
      checked: false
    }],
  },
  
  onLoad: function () {
    console.log(`onLoad`)
    const that = this
    // 页面加载时处理
    searchItems('问题管理表', '标签')
    .then((res) => {
      if (res != 0) {
        console.log(`标签：${res}`)
        console.log(res)
        const items = []
        for (let i = 0; i < res.length; i++) {
          item = {}
          item.value = res[i]
          item.name = res[i]
          item.checked = false
          items[i] = item
        }
        this.setData({
          tags: items
        })
        console.log(this.data.tags)
      } else {
        console.log('update group question failed')
      }
    })
  },
  onShow: function () {
    console.log(`onShow`)
  },
  onQuestionInput: function(e) {
    this.setData({
      question: e.detail.value
    });
  },
  onAnswerInput: function(e) {
    this.setData({
      answer: e.detail.value
    });
  },
  confirmPublish: function() {
    const that = this
    if (!this.data.question) {
      tt.showToast({
        title: '问题不能为空',
        icon: 'none'
      });
      return;
    } else {
      tt.showModal({
        "content": "确认提交此问题？",
        "confirmText": "确认",
        "cancelText": "取消",
        "showCancel": true,
        success(res) {
          console.log('确认')
          console.log(JSON.stringify(res));
          if (res['confirm']) {
            that.onConfirm()
          } else if (res['cancel']) {
            that.onCancel()
          }
        },
        fail(res) {
          console.log("显示弹窗失败")
        }
      })
    }
  },
  onConfirm: function() {
    // 发送网络请求向数据库添加问题
    const app = getApp()
    const tags = this.data.tags
    const that = this
    tagData = []
    index = 0
    for (let i = 0; i < tags.length; i++) {
      if (tags[i].checked) {
        tagData[index] = tags[i].name
        index = index + 1
      }
    }
    console.log(`tags data`)
    console.log(tags)
    console.log(tagData)
    addRecord('问题管理表', [this.data.question, this.data.answer, app.globalData.week, app.globalData.classInfo['组号'], tagData, '未完成', that.data.dataArray, app.globalData.classInfo['姓名'], ''])
    this.goBack()
  },
  onCancel: function() {
  },
  goBack: function() {
    tt.navigateBack();
  },
  checkboxChange: function (e) {
    console.log('Checkbox change，value：', e.detail.value);
    const tags = this.data.tags; // 绑定到页面的数据是 tags
    const values = e.detail.value;
  
    for (let i = 0, lenI = tags.length; i < lenI; ++i) {
      tags[i].checked = false; // 先清空所有选中状态
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (tags[i].value === values[j]) {
          tags[i].checked = true;
          break;
        }
      }
    }
  
    this.setData({
      tags: tags // 更新 tags 数据
    });
  },

  onAddAttachment() {
    const that = this
    tt.chooseMedia({
      mediaType: [
          "image",
          "video"
      ],
      sourceType: [
          "album"
      ],
      count: 5,
      sizeType: [
          "compressed",
          "original"
      ],
      maxDuration: 60,
      cameraDevice: "back",
      isSaveToAlbum: '0',
      success(res) {
        console.log(`chooseMedia success: ${JSON.stringify(res)}`);
        let dataArray = res.tempFiles
        console.log(dataArray);
      
        that.setData({ 
          dataArray: that.sortAttachments(dataArray)
        })
      },
      fail(res) {
        console.log(`chooseMedia fail: ${JSON.stringify(res)}`);
      }
    });
  },
  previewImage: function(e) {
    var current = e.target.dataset.src
    const { dataArray } = this.data
    console.log(`dataArray: ${JSON.stringify(dataArray)}`);
    // let urls = dataArray.map((item, index, array) => {
    //     if (item.type == 'image') {
    //         return item.tempFilePath
    //     }
    // })
    let urls = dataArray.filter(item => item.type == 'image' ).map(item => item.tempFilePath)
    console.log(`urls: ${JSON.stringify(urls)}`);
    tt.previewImage({
        current: current,
        urls: urls,
        success: res => {
            console.log(`previewImage success: ${JSON.stringify(res)}`)
            console.log(`this.data.tags: ${JSON.stringify(this.data.tags)}`)
        },
        fail: res => {
            console.log(`previewImage fail: ${JSON.stringify(res)}`)
        }
    })
  },
  sortAttachments(dataArray) {
    // 排序规则：图片在前，视频在后
    return dataArray.sort((a, b) => {
      if (a.type === 'image' && b.type === 'video') return -1;
      if (a.type === 'video' && b.type === 'image') return 1;
      return 0;
    });
  },
})